<?php
class IndexAction extends CommonAction {
    public function index(){
        C('TOKEN_ON',false);
        $nav = M('InfoNav');
        $info = M('Info');

        //列出分类和信息
        $indexInfo = $nav->field(array('id', 'name'))->where('pid=0')->select();
        foreach($indexInfo as $key=>&$value) {           //获取旗下所有子类id
            $temp = $nav->field('id')->where('pid='.$value['id'])->select();
            foreach($temp as $k=>&$v) {
                $value['childId'] .= $v['id'].',';
            }
            $value['childId'] = substr($value['childId'], 0 ,-1);
            $map['i.cid'] = array('in', $value['childId']);
            $value['info'] = $info->alias('i')
                                  ->field(array('i.id, i.title, n.name, i.addtime, n.id as nid'))
                                  ->join('xinxi_info_nav as n ON i.cid=n.id')
                                  ->where($map)
                                  ->order('i.addtime DESC')
                                  ->limit(6)
                                  ->select();
        }

        //热点信息
        $hotInfo = $info->field(array('id', 'title'))
                        ->order('view_count DESC')
                        ->limit(9)
                        ->select();

        //推广者cookie
        if(isset($_GET['proid'])) {

            $proid = $this->_get('proid');
            $user = M('User');
            //检查推广者最后登录ip是否与本次访问者ip一致，不一致才算有效
            if($user->where('id='.$proid)->getField('last_ip') != $_SERVER['REMOTE_ADDR']) {
                setcookie('proid', $proid, time()+3600*24, '/');          //推广者cookie被记录
            }
        }

        //首页信息随机置顶
        $topInfo = $info->field(array('id', 'title', 'content', 'stick', 'stick_time', 'stick_days'))
                        ->where('stick=3')
                        ->order('RAND()')
                        ->select();

        foreach($topInfo as $key=>&$value) {
            //判断置顶是否过期
            if(($value['stick_time'] + $value['stick_days']) - time() < 0) {
                $data['stick'] = 0;
                $data['stick_time'] = '';
                $data['stick_days'] = '';
                $info->where('id='.$value['id'])->save($data);
            }

        }

        //显示广告
        parent::showBanner();

        //显示帮助
        parent::showAbout();

        $this->assign(array(
           'indexinfo'=>$indexInfo,
           'hotinfo'=>$hotInfo,
           'topinfo'=>$topInfo
        ));

        $this->display();
    }

}

